<template>
  <view class="login-container">
    <!-- 导航栏 -->
    <up-navbar :title="''" left-icon-color="#ffffff" bg-color="transparent" :border="false" :safeAreaInsetTop="true" :autoBack="true">
      <template #right>
        <view class="language-btn" @click="goToLanguagePage">
          <u-icon name="/static/login/language.png" size="40rpx" color="#12C284"></u-icon>
        </view>
      </template>
    </up-navbar>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 品牌标识 -->
      <view class="brand-section">
        <view class="logo">
          <image class="logo-image" src="/static/logo.png" mode="aspectFit" />
        </view>
        <view class="brand-name">
          <text class="brand-title">NEXA</text>
          <text class="brand-subtitle">EXWORTH</text>
        </view>
      </view>

      <!-- 登录方式切换 -->
      <view class="login-tabs">
        <view class="tab-item" :class="{ active: !isSmsLogin }" @click="switchToPasswordLogin">
          <text class="tab-text">{{ useT('密码登录') }}</text>
        </view>
        <view class="tab-item" :class="{ active: isSmsLogin }" @click="switchToSmsLogin">
          <text class="tab-text">{{ useT('验证码登录') }}</text>
        </view>
      </view>

      <!-- 输入区域 -->
      <view class="input-section">
        <!-- 邮箱输入框 -->
        <view class="input-group">
          <view class="input-wrapper">
            <input class="input-field" type="text" :placeholder="useT('输入邮箱')" v-model="email" />
          </view>
        </view>

        <!-- 验证码输入框 (短信登录) -->
        <view class="input-group" v-if="isSmsLogin">
          <view class="input-wrapper">
            <input class="input-field" type="number" :placeholder="useT('输入验证码')" v-model="verificationCode" maxlength="6" />
            <view class="get-code-btn" @click="getVerificationCode">
              <text class="get-code-text">{{ countdown > 0 ? countdown + 's' : useT('验证码') }}</text>
            </view>
          </view>
        </view>

        <!-- 密码输入框 (密码登录) -->
        <view class="input-group" v-else>
          <view class="input-wrapper">
            <input class="input-field" type="password" :placeholder="useT('填写登录密码')" v-model="password" />
          </view>
        </view>
      </view>

      <!-- 下一步按钮 -->
      <view class="next-btn-wrapper">
        <view class="next-btn" @click="handleNext">
          <text class="next-btn-text">{{ useT('立即登录') }}</text>
        </view>
      </view>

      <!-- 去注册入口 -->
      <view class="register-link-wrapper">
        <text class="register-link-text">{{ useT('还没有账号？') }}</text>
        <text class="register-link" @click="goToRegister">{{ useT('去注册') }}</text>
      </view>

      <!-- 用户协议 -->
      <view class="agreement-section">
        <view class="agreement-checkbox" @click="toggleAgreement">
          <view class="checkbox" :class="{ checked: isAgreed }">
            <text class="checkmark" v-if="isAgreed">✓</text>
          </view>
          <text class="agreement-text">
            {{ useT('已阅读并同意') }}
            <text class="link-text" @click.stop="showUserAgreement">{{ useT('《用户协议》') }}</text>
            &
            <text class="link-text" @click.stop="showPrivacyPolicy">{{ useT('服务协议与隐私政策') }}</text>
          </text>
        </view>
      </view>
    </view>

    <!-- 协议弹窗 -->
    <up-popup v-model:show="showAgreementPopup" mode="center" :round="20" :closeable="false" :closeOnClickOverlay="false">
      <view class="agreement-popup">
        <view class="popup-title">{{ useT('服务协议与隐私政策') }}</view>
        <view class="popup-content">
          <text>{{ useT('已阅读并同意') }}</text>
          <text class="link-text" @click.stop="showUserAgreement">{{ useT('《用户协议》') }}</text>
          <text>&</text>
          <text class="link-text" @click.stop="showPrivacyPolicy">{{ useT('服务协议与隐私政策') }}</text>
        </view>
        <view class="popup-buttons">
          <up-button type="default" :text="useT('取消')" :custom-style="{ width: '200rpx', height: '80rpx', marginRight: '20rpx' }" @click="closeAgreementPopup" />
          <up-button type="primary" :text="useT('我同意')" :custom-style="{ width: '200rpx', height: '80rpx' }" @click="agreeAndLogin" />
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { loginByPassword, loginBySms, sendSmsCode, SMS_EVENTS, THIRD_PARTY_PLATFORMS, thirdPartyLogin, validateCaptcha, validatePassword } from '@/api/login.js';
import { updateUserInfo } from '@/api/user.js';
import { goToWebView } from '@/config/webViewConfig.js';
import { useUserStore } from '@/stores/user.js';
import { useT } from '@/utils/i18n.js';
import { onMounted, onUnmounted, ref } from 'vue';

// 响应式数据
const email = ref('');
const verificationCode = ref('');
const password = ref('');
const isAgreed = ref(false);
const countdown = ref(0);
const timer = ref(null);
const isSmsLogin = ref(true); // true: 验证码登录, false: 密码登录
const showAgreementPopup = ref(false); // 控制协议弹窗显示

// 生命周期钩子
onMounted(() => {
  // 页面加载
});

onUnmounted(() => {
  // 清理定时器
  if (timer.value) {
    clearInterval(timer.value);
  }
});

// 方法
// 切换到密码登录
const switchToPasswordLogin = () => {
  isSmsLogin.value = false;
  // 清空输入内容
  verificationCode.value = '';
  // 清除倒计时
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  countdown.value = 0;
};

// 切换到验证码登录
const switchToSmsLogin = () => {
  isSmsLogin.value = true;
  // 清空输入内容
  password.value = '';
};

// 邮箱验证函数
const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 跳转到语言选择页面
const goToLanguagePage = () => {
  uni.navigateTo({
    url: '/pagesD/setting/language'
  });
};

// 处理下一步
const handleNext = () => {
  if (isSmsLogin.value) {
    handleLogin();
  } else {
    handleLogin();
  }
};

// 获取验证码
const getVerificationCode = async () => {
  if (countdown.value > 0) return;

  // 验证邮箱格式
  if (!validateEmail(email.value)) {
    uni.showToast({
      title: useT('请输入正确的邮箱'),
      icon: 'none'
    });
    return;
  }

  try {
    uni.showLoading({
      title: useT('发送中.')
    });

    // 调用发送验证码API（接口字段名保持不变）
    const result = await sendSmsCode({
      phone: email.value, // 字段名保持phone，但传邮箱值
      type: SMS_EVENTS.LOGIN
    });

    uni.hideLoading();
    console.log('====>result', result);

    if (result.status === 200) {
      // 开始倒计时
      countdown.value = 60;
      timer.value = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer.value);
          timer.value = null;
        }
      }, 1000);

      uni.showToast({
        title: result.msg,
        icon: 'success'
      });
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error || useT('发送失败，请重试'),
      icon: 'none'
    });
  }
};

// 处理登录
const handleLogin = () => {
  // 验证邮箱格式
  if (!validateEmail(email.value)) {
    uni.showToast({
      title: useT('请输入正确的邮箱'),
      icon: 'none'
    });
    return;
  }

  // 检查验证码或密码
  if (isSmsLogin.value) {
    if (!validateCaptcha(verificationCode.value)) {
      uni.showToast({
        title: useT('请输入6位验证码'),
        icon: 'none'
      });
      return;
    }
  } else {
    const passwordValidation = validatePassword(password.value);
    if (!passwordValidation.isValid) {
      uni.showToast({
        title: passwordValidation.message,
        icon: 'none'
      });
      return;
    }
  }

  // 检查协议是否同意
  if (!isAgreed.value) {
    showAgreementModal();
    return;
  }

  // 执行登录
  performLogin();
};

// 显示协议弹窗
const showAgreementModal = () => {
  showAgreementPopup.value = true;
};

// 关闭协议弹窗
const closeAgreementPopup = () => {
  showAgreementPopup.value = false;
};

// 同意协议并登录
const agreeAndLogin = () => {
  // 自动勾选协议
  isAgreed.value = true;
  // 关闭弹窗
  showAgreementPopup.value = false;
  // 等待1秒后登录
  setTimeout(() => {
    performLogin();
  }, 1000);
};

// 执行登录
const performLogin = async () => {
  uni.showLoading({
    title: useT('登录中.')
  });

  try {
    let result;

    if (isSmsLogin.value) {
      // 邮箱验证码登录（接口字段名保持不变）
      result = await loginBySms({
        phone: email.value, // 字段名保持phone，但传邮箱值
        captcha: verificationCode.value
      });
    } else {
      // 邮箱密码登录（接口字段名保持不变）
      result = await loginByPassword({
        account: email.value, // 字段名保持account，但传邮箱值
        password: password.value
      });
    }

    uni.hideLoading();
    console.log('====>result', result);
    if (result.status === 200) {
      // 设置用户登录状态
      const userStore = useUserStore();
      userStore.setToken(result.data.token);
      updateUserInfo();
      uni.showToast({
        title: useT('登录成功'),
        icon: 'success'
      });

      // 登录成功后跳转到个人中心
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/tabBar/mine'
        });
      }, 1500);
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error || useT('登录失败，请重试'),
      icon: 'none'
    });
  }
};

// 微信登录（预留功能）
// eslint-disable-next-line no-unused-vars
const wechatLogin = async () => {
  try {
    // 调用微信登录API获取code
    const loginRes = await uni.login({
      provider: 'weixin',
      onlyAuthorize: true
    });
    console.log('====>wechatLogin', loginRes);
    // 检查登录结果
    if (loginRes.errMsg === 'login:ok' && loginRes.code) {
      uni.showLoading({
        title: useT('登录中.')
      });

      const result = await thirdPartyLogin({
        platform: THIRD_PARTY_PLATFORMS.WECHAT,
        code: loginRes.code
      });

      uni.hideLoading();

      if (result.code === 1) {
        // 设置用户登录状态
        const userStore = useUserStore();
        userStore.setUserInfo(
          result.data.userInfo || {
            id: result.data.id,
            name: result.data.name || result.data.username,
            code: result.data.code,
            avatar: result.data.avatar,
            email: result.data.email,
            mobile: result.data.mobile
          }
        );
        userStore.setToken(result.data.token);

        uni.showToast({
          title: useT('登录成功'),
          icon: 'success'
        });

        // 登录成功后跳转到个人中心
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/tabBar/mine'
          });
        }, 1500);
      }
    }
  } catch (error) {
    console.log(error);
    uni.hideLoading();
    uni.showToast({
      title: error || useT('微信登录失败'),
      icon: 'none'
    });
  }
};

// QQ登录（预留功能）
// eslint-disable-next-line no-unused-vars
const qqLogin = async () => {
  try {
    // 调用QQ登录API获取code
    const loginRes = await uni.login({
      provider: 'qq'
    });
    console.log('====>qqLogin', loginRes);
    // 检查登录结果
    if (loginRes.errMsg === 'login:ok' && loginRes.code) {
      uni.showLoading({
        title: useT('登录中.')
      });

      const result = await thirdPartyLogin({
        platform: THIRD_PARTY_PLATFORMS.QQ,
        code: loginRes.code
      });

      uni.hideLoading();

      if (result.code === 1) {
        // 设置用户登录状态
        const userStore = useUserStore();
        userStore.setUserInfo(
          result.data.userInfo || {
            id: result.data.id,
            name: result.data.name || result.data.username,
            code: result.data.code,
            avatar: result.data.avatar,
            email: result.data.email,
            mobile: result.data.mobile
          }
        );
        userStore.setToken(result.data.token);

        uni.showToast({
          title: useT('登录成功'),
          icon: 'success'
        });

        // 登录成功后跳转到个人中心
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/tabBar/mine'
          });
        }, 1500);
      }
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error || useT('QQ登录失败'),
      icon: 'none'
    });
  }
};

// 切换协议同意状态
const toggleAgreement = () => {
  isAgreed.value = !isAgreed.value;
};

// 显示用户协议
const showUserAgreement = () => {
  goToWebView('userAgreement');
};

// 显示隐私政策
const showPrivacyPolicy = () => {
  goToWebView('privacyPolicy');
};

// 显示重置密码页面（预留功能）
// eslint-disable-next-line no-unused-vars
const showResetPasswordModal = () => {
  uni.navigateTo({
    url: '/pages/login/resetPassword'
  });
};

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/login/register'
  });
};
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: #000000;
  position: relative;
}

.status-bar {
  height: var(--status-bar-height);
  background: #000000;
}

.language-btn {
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-content {
  padding: 60rpx 40rpx 40rpx;
  min-height: calc(100vh - var(--status-bar-height));
  box-sizing: border-box;
}

// 品牌标识
.brand-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 120rpx;
  margin-bottom: 80rpx;

  .logo {
    margin-right: 24rpx;

    .logo-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
    }
  }

  .brand-name {
    display: flex;
    flex-direction: column;

    .brand-title {
      font-size: 48rpx;
      font-weight: bold;
      color: #ffffff;
      line-height: 1;
      margin-bottom: 8rpx;
    }

    .brand-subtitle {
      font-size: 32rpx;
      color: #ffffff;
      line-height: 1;
    }
  }
}

// 登录方式切换
.login-tabs {
  display: flex;
  margin-bottom: 60rpx;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    border-bottom: 2rpx solid transparent;
    transition: all 0.3s ease;

    &.active {
      border-bottom-color: #ffffff;
    }

    .tab-text {
      font-size: 32rpx;
      color: #ffffff;
      font-weight: 500;
    }
  }
}

// 输入区域
.input-section {
  margin-bottom: 60rpx;

  .input-group {
    margin-bottom: 40rpx;

    .input-wrapper {
      display: flex;
      align-items: center;
      background: #333333;
      border-radius: 12rpx;
      padding: 0 24rpx;
      height: 88rpx;
      position: relative;

      .input-field {
        flex: 1;
        height: 100%;
        font-size: 32rpx;
        color: #ffffff;
        background: transparent;
        border: none;
        outline: none;
      }

      .input-field::placeholder {
        color: #999999;
      }

      .get-code-btn {
        position: absolute;
        right: 24rpx;
        top: 50%;
        transform: translateY(-50%);
        padding: 8rpx 16rpx;
        background: #ffffff;
        border-radius: 8rpx;
        cursor: pointer;

        .get-code-text {
          color: #000000;
          font-size: 28rpx;
          font-weight: 500;
        }
      }
    }

    .input-hint {
      color: #999999;
      font-size: 24rpx;
      margin-top: 16rpx;
      display: block;
    }

    .invite-label {
      color: #ffffff;
      font-size: 28rpx;
      margin-bottom: 16rpx;
      display: block;
    }
  }
}

// 已有账号链接
.existing-account {
  text-align: right;
  margin-bottom: 60rpx;

  .existing-account-text {
    color: #ffffff;
    font-size: 28rpx;
    text-decoration: underline;
    cursor: pointer;
  }
}

// 下一步按钮
.next-btn-wrapper {
  margin-bottom: 60rpx;

  .next-btn {
    width: 100%;
    height: 88rpx;
    background: #ffffff;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    .next-btn-text {
      color: #000000;
      font-size: 32rpx;
      font-weight: 500;
    }
  }
}

// 去注册入口
.register-link-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;

  .register-link-text {
    font-size: 28rpx;
    color: #999999;
    margin-right: 16rpx;
  }

  .register-link {
    font-size: 28rpx;
    color: #12c284;
    text-decoration: underline;
    cursor: pointer;
  }
}

// 用户协议
.agreement-section {
  display: flex;
  align-items: center;
  justify-content: center;

  .agreement-checkbox {
    display: flex;
    align-items: center;
    cursor: pointer;

    .checkbox {
      width: 32rpx;
      height: 32rpx;
      border: 2rpx solid #cccccc;
      border-radius: 50%;
      margin-right: 16rpx;
      margin-top: 4rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      &.checked {
        background: #ffffff;
        border-color: #ffffff;
      }

      .checkmark {
        color: #000000;
        font-size: 20rpx;
        font-weight: bold;
      }
    }

    .agreement-text {
      font-size: 24rpx;
      color: #999999;
      line-height: 1.5;
      flex: 1;

      .link-text {
        color: #ffffff;
        text-decoration: underline;
      }
    }
  }
}

// 协议弹窗
.agreement-popup {
  padding: 60rpx 40rpx 40rpx;
  width: 600rpx;
  text-align: center;
  background: #ffffff;
  border-radius: 20rpx;

  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
    margin-bottom: 30rpx;
  }

  .popup-content {
    font-size: 28rpx;
    color: #666666;
    line-height: 1.6;
    margin-bottom: 50rpx;

    .link-text {
      color: #4a90e2;
      text-decoration: underline;
      margin: 0 8rpx;
    }
  }

  .popup-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
